package com.newway.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newway.LoginUser;
import com.newway.common.Result;
import com.newway.util.JwtTokenUtil;
import com.newway.wechat.context.UserInfo;
import com.newway.wechat.context.UserInfoContext;
import com.newway.wechat.entity.LoginRecord;
import com.newway.wechat.entity.UserInfoEntity;

import com.newway.wechat.mapper.LoginRecordMapper;
import com.newway.wechat.mapper.UserInfoMapper;
import com.newway.util.HttpUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/wechat")
public class UserController {

    /*
    * GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    * */

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    LoginRecordMapper loginRecordMapper;

    @Autowired
    Environment environment;


    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginUser loginUser){
        String openId = getOpenId(loginUser.getId());
        UserInfoEntity userInfo = userInfoMapper.selectById(openId);
        if(userInfo==null){
            userInfo = new UserInfoEntity();
            userInfo.setId(openId);
            userInfo.setAvatar(loginUser.getAvatar());
            userInfo.setNickName(loginUser.getUserName());
            userInfo.setCreateTime(new Date());
            userInfo.setTenantId(UUID.randomUUID().toString().replace("-",""));
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            userInfo.setRegisterTime(simpleDateFormat.format(date));
            userInfoMapper.insert(userInfo);
        }
        //UserInfo userInfo1 = getLoginCounts(userInfo);
        loginUser.setUserInfo(getLoginCounts(userInfo));
        String token = jwtTokenUtil.createToken(loginUser);
        return Result.success(token);
    }

    /**
     * 统计用户登录天数
     * @param userInfo
     * @return
     */
    private UserInfo getLoginCounts(UserInfoEntity userInfo) {
        UserInfo userInfo1 = new UserInfo();
        BeanUtils.copyProperties(userInfo,userInfo1);
        //登录成功，记录登录数据
        // 获取当天的开始时间和结束时间
        LocalDateTime beginTime = LocalDate.now().atTime(LocalTime.MIN);
        LocalDateTime endTime = LocalDate.now().atTime(LocalTime.MAX);
        // 获取上一天的开始时间和结束时间
        LocalDateTime beginTime1 = LocalDate.now().minusDays(1).atTime(LocalTime.MIN);
        LocalDateTime endTime1 = LocalDate.now().minusDays(1).atTime(LocalTime.MAX);
        // 构建查询条件
        LambdaQueryWrapper<LoginRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(LoginRecord::getCreateTime, beginTime1);
        queryWrapper.le(LoginRecord::getCreateTime, endTime1);
        queryWrapper.eq(LoginRecord::getUserId,userInfo.getId());
        LoginRecord yesterday = loginRecordMapper.selectOne(queryWrapper);
        LambdaQueryWrapper<LoginRecord> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.ge(LoginRecord::getCreateTime, beginTime);
        queryWrapper1.le(LoginRecord::getCreateTime, endTime);
        LoginRecord today = loginRecordMapper.selectOne(queryWrapper1);
        if(yesterday==null){
            //再看今天有没有数据
            if(today==null){
                today = new LoginRecord();
                today.setUserId(userInfo.getId());
                today.setCountDays(1);
                today.setCreateTime(LocalDateTime.now());
                loginRecordMapper.insert(today);
            }
        }else {
            if(today==null){
                today = new LoginRecord();
                today.setUserId(userInfo.getId());
                today.setCountDays(yesterday.getCountDays()+1);
                today.setCreateTime(LocalDateTime.now());
                loginRecordMapper.insert(today);
            }
        }
        int continuesTotals = today.getCountDays();
        QueryWrapper<LoginRecord> loginRecordQueryWrapper = new QueryWrapper<>();
        loginRecordQueryWrapper.eq("user_id",userInfo.getId());
        Long loginTotals = loginRecordMapper.selectCount(loginRecordQueryWrapper);
        userInfo1.setLoginTotals(loginTotals);
        userInfo1.setContinuesTotals(continuesTotals);
        return userInfo1;
    }

    @GetMapping("/userInfo")
    public Result<UserInfo> userInfo(){
        UserInfo userInfo = UserInfoContext.getUserInfo();
        return Result.success(userInfo);
    }

    @PostMapping("/updateUserInfo")
    public Result updateUserInfo(@RequestParam("file") MultipartFile file, @ModelAttribute UserInfo updateInfo,HttpServletRequest request){
        String UPLOAD_DIR = environment.getProperty("img.uploadPath");
        String mappingPath = environment.getProperty("img.mappingPath");
        try {
            LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            File uploadPath = new File(UPLOAD_DIR);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            String fileName = UUID.randomUUID() + fileExtension;
            File dest = new File(uploadPath.getAbsolutePath() + File.separator + fileName);
            file.transferTo(dest);
            UserInfo userInfo = UserInfoContext.getUserInfo();
            UserInfoEntity userInfoEntity = userInfoMapper.selectById(userInfo.getId());
            if(StringUtils.isNotBlank(fileName)){
                userInfoEntity.setAvatar(mappingPath+fileName);
                userInfo.setAvatar(mappingPath+fileName);
                loginUser.setAvatar(mappingPath+fileName);
            }
            if(StringUtils.isNotBlank(updateInfo.getNickName())){
                userInfoEntity.setNickName(updateInfo.getNickName());
                userInfo.setNickName(updateInfo.getNickName());
                loginUser.setUserName(updateInfo.getNickName());
            }
            if(StringUtils.isNotBlank(updateInfo.getPhoneNo())){
                userInfoEntity.setPhoneNo(updateInfo.getPhoneNo());
                userInfo.setPhoneNo(updateInfo.getPhoneNo());
            }
            userInfoMapper.updateById(userInfoEntity);
            loginUser.setUserInfo(userInfo);
            jwtTokenUtil.refreshToken(loginUser);
            return Result.success(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail("修改信息失败");
        }
    }

    @PostMapping("/updateUserInfo1")
    public Result updateUserInfo1(@RequestBody UserInfo updateInfo,HttpServletRequest request){
        LoginUser loginUser = jwtTokenUtil.getLoginUser(request);
        UserInfo userInfo = UserInfoContext.getUserInfo();
        UserInfoEntity userInfoEntity = userInfoMapper.selectById(userInfo.getId());
        if(StringUtils.isNotBlank(updateInfo.getNickName())){
            userInfoEntity.setNickName(updateInfo.getNickName());
            userInfo.setNickName(updateInfo.getNickName());
            loginUser.setUserName(updateInfo.getNickName());
        }
        int i = userInfoMapper.updateById(userInfoEntity);
        loginUser.setUserInfo(userInfo);
        jwtTokenUtil.refreshToken(loginUser);
        return Result.success(userInfo);
    }

    public String getOpenId(String wxCode){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wxdf862d46e880fe72&secret=7c88b5c2c758767d047b881258ad42d4&js_code="+wxCode+"&grant_type=authorization_code";
        String result = HttpUtil.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(result);
        Object openId = jsonObject.get("openid");
        return openId.toString();
    }

}
